package com.gitee.form_token.token;

import cn.hutool.core.util.StrUtil;
import com.gitee.form_token.common.Const;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * App 自定义处理
 * -- 令牌校验
 **/
@Component
public class CheckAppToken {

    public static String getSubject(HttpServletRequest request) {
        String token = request.getHeader(Const.Authorization);

        // 统一使用BadCredentialsException处理所有认证相关错误
        if (StrUtil.isBlank(token)) {
            throw new BadCredentialsException("令牌缺失");
        }

        Claims claims;
        try {
            claims = JwtUtil.getClaims(token, Const.AppIssuerKey);
            if (claims == null) {
                throw new BadCredentialsException("令牌异常");
            }

            if (JwtUtil.isExpired(claims)) {
                throw new BadCredentialsException("令牌过期");
            }

            String subject = claims.getSubject();
            if (StrUtil.isBlank(subject)) {
                throw new BadCredentialsException("令牌无效");
            }

            if (JwtUtil.isExpired(claims)) {
                throw new BadCredentialsException("令牌过期");
            }

            return subject;

        } catch (Exception ex) {
            throw new BadCredentialsException("无效令牌: " + ex.getMessage());
        }
    }

}
